<template>
  <a-card :bordered="false" style="width: 1720px;">
    <excel-paste
      :columnsExcel="excelColumns"
      :exportXlsTemplateUrl="excel.templateUrl"
      :excelVisible="excel.visible"
      :excelConfirmLoading="excel.loading"
      @handleOkExcel="handleOkExcel"
      @handleCancelExcel="handleCancelExcel"
    ></excel-paste>
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="26">
          <a-col :md="12" :sm="12">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="doSave" :disabled="buttonDisabled">保存并生成附件</a-button>
              <a-button @click="doImpl" style="margin-left:10px;" :disabled="buttonDisabled">导入</a-button>
              <a-button @click="handlePostExportXls('工程项目变更报表')" style="margin-left: 8px" :disabled="buttonDisabled">导出</a-button>
              <a-button @click="doAdd" style="margin-left: 8px" :disabled="buttonDisabled">添加</a-button>
              <a-button @click="doDel" style="margin-left: 8px" :disabled="buttonDisabled">删除</a-button>
              <a-button @click="jumpHaiNa" style="margin-left: 8px" :disabled="buttonDisabled">海纳闲置设备库</a-button>
            </span>
          </a-col>
          <a-col :md="10" :sm="10">
            <h3 style="margin-top:4px;font-weight:bold">
              项目编号：{{projectNo}} &nbsp;&nbsp;&nbsp;&nbsp;项目名称：{{projectName}}
            </h3>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col style="margin-left: 500px;">
            <h4 style="color:red;">请优先考虑使用闲置设备,以节约项目成本,消耗呆滞物料!</h4>
          </a-col>
        </a-row>
      </a-form>

      
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
    </div>
    <div class="container" >
      <a-table
        ref="table"
        bordered
        size="middle"
        :scroll="{x:true}"
         :rowKey="rowKey"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,columnWidth:40}"
        :loading="loading">
        <template 
        slot="budgetType"
        slot-scope="text, record, index">
          <div key="budgetType">
            <a-textarea auto-size v-if="editable"  required 
            style="margin: -5px 0" :maxLength="100"
            v-model="record.budgetType"/>
            <span v-else :title="record.budgetType">{{showLength(record.budgetType,15)}}</span>
          </div>
        </template>
        <template 
        slot="budgetItem"
        slot-scope="text, record, index">
          <div key="budgetItem">
            <a-textarea auto-size v-if="editable" 
            style="margin: -5px 0" :maxLength="250"
            v-model="record.budgetItem"/>
            <span v-else :title="record.budgetItem">{{showLength(record.budgetItem,15)}}</span>
          </div>
        </template>
        <template 
        slot="unit"
        slot-scope="text, record, index">
          <div key="unit">
            <a-textarea auto-size v-if="editable" 
            style="margin: -5px 0"  :maxLength="50"
            v-model="record.unit"/>
            <span v-else :title="record.unit">{{showLength(record.unit,15)}}</span>
          </div>
        </template>
        <template 
        slot="remark"
        slot-scope="text, record, index">
          <div key="remark">
            <a-textarea auto-size v-if="editable" 
            style="margin: -5px 0"  :maxLength="500"
            v-model="record.remark"/>
            <span v-else :title="record.remark">{{showLength(record.remark,15)}}</span>
          </div>
        </template>
        
        <template 
        slot="sharedPersons"
        slot-scope="text, record, index">
          <div key="sharedPersons">
            
            <UserInputSelector :username.sync="record.sharedPersons"
              :realname.sync="record.sharedPersonsName" :disabled="false"
              multiple="multiple" placeholder="请选择"/>

            <!--<a-select v-model:value="record.sharedPersons" mode="tags" style="width: 100%"
              placeholder="Tags Mode" :options="options" @change="handleChange"></a-select> -->

            <!-- <a-textarea auto-size v-if="editable" 
            style="margin: -5px 0"  :maxLength="500"
            v-model="record.sharedPersons"/> -->
            
            <!--<span  :title="record.sharedPersons">{{showLength(record.sharedPersons,30)}}</span>
            <i class="el-icon-search" @click="showModal(1,index)"></i> -->
            
            <!--<span v-else :title="record.sharedPersons">{{showLength(record.sharedPersons,15)}}</span>-->
          </div>
        </template>
        <template 
        slot="responsiblePersons"
        slot-scope="text, record, index">
          <div key="responsiblePersons">

            <UserInputSelector :username.sync="record.responsiblePersons"
              :realname.sync="record.responsiblePersonsName" :disabled="false"
              multiple="multiple" placeholder="请选择"/>

            <!-- <a-textarea auto-size v-if="editable" 
            style="margin: -5px 0"  :maxLength="500"
            v-model="record.responsiblePersons"/>  -->
            
            <!--<span  :title="record.responsiblePersons">{{showLength(record.responsiblePersons,30)}}</span>
            <i class="el-icon-search" @click="showModal(2,index)"></i>-->

          </div>
        </template>



        <template 
        v-for="col in ['num','includeTaxPriceUnit','taxRate','noTaxPriceUnit','includeTaxPriceAll','noTaxPriceAll']"
        :slot="col"
        slot-scope="text, record, index">
          <div :key="col">
            <a-input v-if="editable" type="number"
            style="margin: -5px 0"
            v-model="record[col]"/>
            <template v-else>{{record[col]}}</template>
          </div>
        </template>
        
      </a-table>

    </div>

    <!-- userlist dialog -->
    <div>
    <!--<a-button type="primary" @click="showModal">Open Modal</a-button>-->
      <!--<a-modal v-model:visible="userListVisible" title="用户列表" @ok="handleOk">-->
        <!-- 选项,排序编号,账号,名称 -->
        <!--<a-table 
        :dataSource="userDataSource" 
        :columns="userColumns"
        :pagination="pagination"
        :rowSelection="{selectedRowKeys: userSelectedRowKeys,onChange: userOnSelectChange,columnWidth:40}" /> -->
      <!--</a-modal>-->
    </div>
    
  </a-card>
</template>


<script>
import { getAction, getActionAsync, postAction, postActionAsync } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListSearchMixin'
import { getParamValFromUrl, strNotNull } from '@/utils/common.js'
import ExcelPaste from '@/components/excelPaste/ExcelPaste'
export default {
  components: { 
    ExcelPaste 
   },
  name: 'engineeBudget',
  mixins: [JeecgListMixin],
  props:{
    projectBuildId:{
      Type:String,
      default:''
    },
    projectNo:{
      Type:String,
      default:''
    },
    projectName:{
      Type:String,
      default:''
    },
    canEditPage:{
      Type:Boolean,
      default:true
    },
  },
  data() {
    return {
      description: '工程项目预算表',
      /* 勾选导出参数 */
      rowKey:'strId',
      editable:true,
      addNum: 1,
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 40,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '预算分类',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'budgetType' }
        },
        {
          title: '预算项',
          align: 'center',
          width: 180,
          scopedSlots: { customRender: 'budgetItem' }
        },
        {
          title: '单位',
          align: 'center',
          width: 100,
          scopedSlots: { customRender: 'unit' }
        },
        {
          title: '数量',
          align: 'center',
          width: 100,
          scopedSlots: { customRender: 'num' }
        },
        {
          title: '含税单价（万元）',
          align: 'center',
          width: 100,
          scopedSlots: { customRender: 'includeTaxPriceUnit' }
        },
        {
          title: '税率',
          align: 'center',
          width: 100,
          scopedSlots: { customRender: 'taxRate' }
        },
        {
          title: '不含税单价（万元）',
          align: 'center',
          width: 100,
          scopedSlots: { customRender: 'noTaxPriceUnit' }
        },
        {
          title: '含税总价（万元）',
          align: 'center',
          width: 100,
          scopedSlots: { customRender: 'includeTaxPriceAll' }
        },
        {
          title: '不含税总价（万元）',
          align: 'center',
          width: 100,
          scopedSlots: { customRender: 'noTaxPriceAll' }
        },
        {
          title: '共享人',
          align: 'center',
          width: 200,
          scopedSlots: { customRender: 'sharedPersons' }
        },
        {
          title: '负责人',
          align: 'center',
          width: 200,
          scopedSlots: { customRender: 'responsiblePersons' }
        },
        {
          title: '备注',
          align: 'center',
          width: 200,
          scopedSlots: { customRender: 'remark' }
        }
      ],
      excelColumns: [
        {
          title: '预算分类',
          dataIndex: 'budgetType',
          width: 100
        },
        {
          title: '预算项',
          dataIndex: 'budgetItem',
          width: 120
        },
        {
          title: '单位',
          dataIndex: 'unit',
          width: 60
        },
        {
          title: '数量',
          dataIndex: 'num',
          width: 60
        },
        {
          title: '含税单价（万元）',
          dataIndex: 'includeTaxPriceUnit',
          width: 60
        },
        {
          title: '税率',
          dataIndex: 'taxRate',
          width: 50
        },
        {
          title: '不含税单价（万元）',
          dataIndex: 'noTaxPriceUnit',
          width: 60
        },
        {
          title: '含税总价（万元）',
          dataIndex: 'includeTaxPriceAll',
          width: 60
        },
        {
          title: '不含税总价（万元）',
          dataIndex: 'noTaxPriceAll',
          width: 60
        },
        {
          title: '共享人',
          dataIndex: 'sharedPersons',
          width: 120
        },
        {
          title: '负责人',
          dataIndex: 'responsiblePersons',
          width: 120
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: 120
        }
      ],
      url: {
        add: '/projectBudgetEnginee/add',
        list: '/projectBudgetEnginee/list',
        exportXlsUrl: '/projectBudgetEnginee/exportXls',
        deleteBatch: '/projectBudgetEnginee/deleteBatch',
        getHaiNaUrl:'/projectBudgetEnginee/getHaiNaUrl',
        userList:'/projectBudgetEnginee/userList',
        personListByUserNames: '/person/info/personListByUserNames',
      },
      excel: {
        visible: false,
        loading: false,
        data: [],
        templateUrl: 'templates/excel/工程项目预算表.xlsx',
      },
      showSearchForm: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      saveDisabled: false,
      buttonDisabled:false,
      //userListVisible:false,
      //userSelectedRowKeys:[],
      //userSelectAccount:[],
      //currentPersonType:'sharedPersons',
      //currentSelectRow:0,
      // userDataSource:[
      //   //{key:'1',username:'parker',realname:'帕克',sex:'1'},
      //   //{key:'2',username:'linda',realname:'琳达',sex:'2'}
      // ],
      // userColumns:[
      //   {
      //     title:'用户名',
      //     dataIndex:'username',
      //     key:'username'
      //   },
      //   {
      //     title:'中文名',
      //     dataIndex:'realname',
      //     key:'realname'
      //   },
      //   {
      //     title:'性别',
      //     dataIndex:'sex',
      //     key:'sex' 
      //   }
      // ],
      //userCurrentPage:1,
      //userTotal:0
      //pagination:{total:0,current:1,pageSize:10}
    }
  },
  mounted() {
    console.log('created this.projectBuildId:',this.projectBuildId)
    console.log('created this.canEditPage:',this.canEditPage)
    if(this.canEditPage){
      this.buttonDisabled = false
    }else{
      this.buttonDisabled = true
    }
    this.getList()
    //this.setEngineeBudgetData()
  },

  created(){
    // console.log('created this.projectBuildId:',this.projectBuildId)
    // console.log('created this.canEditPage:',this.canEditPage)
    // if(this.canEditPage){
    //   this.buttonDisabled = false
    // }else{
    //   this.buttonDisabled = true
    // }
    // this.getList()
    //console.log('hahahah')
    
  },

  computed: {},
  methods: {

    getCurrentTableList(){
      return this.dataSource;
    },

    // setEngineeBudgetData(){
    //   this.engineeBudgetData = []
    //   this.engineeBudgetData = this.dataSource
    //   console.log('设置最新的engineeBudgetData',this.engineeBudgetData)
    // },

    getList(){
      let postParams = {projectBuildId:this.projectBuildId}
      let postUrl = this.url.list
      postAction(postUrl,postParams).then((res)=>{
        if(res.code === 200){
          //console.log('获取预算工程列表数据:',JSON.stringify(res))
          this.dataSource = res.result.records
        }else{
          this.$message.error('获取预算工程列表失败')
        }
      })
    },

    // userOnSelectChange(e){
    //     this.userSelectedRowKeys = e
    // },
    // showModal(type = 1,index = 0){
    //   console.log('type:',type)
    //   console.log('index:',index)
    //   if(type == 1){
    //     this.currentPersonType = 'sharedPersons'
    //   }else if(type == 2){
    //     this.currentPersonType = 'responsiblePersons'
    //   }
    //   this.currentSelectRow = index
    //   this.userListVisible = true

    //   // 获取用户列表
    //   let postParams = {username:'',page:1,pageSize:10};
    //   let postUrl = this.url.userList;
    //   postAction(postUrl,postParams).then((res)=>{
    //     if(res.code === 200){
    //       let data = res.result
    //       this.userDataSource = data.records
    //       this.pagination.total = data.total
    //       //this.userTotal =  data.total
    //     }else{
    //       this.$message.error('获取用户列表失败')
    //     }
    //   })
    // },
    // handleOk(e){
    //   this.userSelectAccount = []
    //   for(let i = 0; i < this.userSelectedRowKeys.length; ++i){
    //         let pos = this.userSelectedRowKeys[i];
    //         this.userSelectAccount.push(this.userDataSource[pos - 1].username)
    //   }
    //   console.log(this.userSelectAccount)
    //   if(this.currentPersonType == 'sharedPersons'){
    //     this.dataSource[this.currentSelectRow].sharedPersons = this.userSelectAccount.toString()
    //   }else if(this.currentPersonType == 'responsiblePersons'){
    //     this.dataSource[this.currentSelectRow].responsiblePersons = this.userSelectAccount.toString()
    //   }
    //   this.userSelectAccount = []
    //   this.userSelectedRowKeys=[]
    //   this.userListVisible = false
    // },

    msgNoNull(i,name){
      return '第['+(i+1)+']行,['+name+']不可为空';
    },
    msgBigerZero(i,name){
      return '第['+(i+1)+']行,['+name+']必须大于0';
    },
    doSave(){
      if(this.saveDisabled){
        this.$message.warning('请勿暴力点击')
        return;
      }
      this.saveDisabled=true;
      if(!this.doCheck(this.dataSource)){
        this.saveDisabled=false;
        return;
      }
      var formData = JSON.parse(JSON.stringify(this.dataSource));
      console.log(formData)
      postAction(this.url.add+'?buildId='+this.projectBuildId, formData).then((res) => {
        this.saveDisabled=false;
            if (res.code == 200) {
              this.$message.success('操作成功')
              this.searchQuery()
              this.setEngineeBudgetData()
            } else {
              this.$message.warning('操作失败:' + res.message)
            }
          }).catch((res) => {
            this.saveDisabled=false;
            this.$message.warning('操作异常:' + res.message)
          })
      
    },
    doCheck(data){
      for(var i=0;i<data.length;i++){
        var item=data[i];
        if(!strNotNull(item.budgetType)){
          this.$message.warning(this.msgNoNull(i,'预算分类'))
          return false;
        }
        if(!strNotNull(item.budgetItem)){
          this.$message.warning(this.msgNoNull(i,'预算项'))
          return false;
        }
        if(item.num<=0){
          this.$message.warning(this.msgBigerZero(i,'数量'))
          return false;
        }
        if(item.includeTaxPriceUnit<=0){
          this.$message.warning(this.msgBigerZero(i,'含税单价（万元）'))
          return false;
        }
        if(item.taxRate<=0){
          this.$message.warning(this.msgBigerZero(i,'税率'))
          return false;
        }
        if(item.noTaxPriceUnit<=0){
          this.$message.warning(this.msgBigerZero(i,'不含税单价（万元）'))
          return false;
        }
      }
      return true;
    },
    doAdd(){
      this.doAddData('','','',0,0,0,0,0,0,'','','','','')
    },
    doAddData(type,item,unit,num,itpu,tr,npu,itpa,npa,remark,sharedPersons,responsiblePersons,sharedPersonsName,responsiblePersonsName){
      this.dataSource.push({
        id: null,
        strId: 'add_'+this.addNum,
        budgetType: type,
        budgetItem: item,
        unit: unit,
        num: num,
        includeTaxPriceUnit: itpu,
        taxRate: tr,
        noTaxPriceUnit: npu,
        includeTaxPriceAll: itpa,
        noTaxPriceAll: npa,
        remark: remark,
        sharedPersons:sharedPersons,
        responsiblePersons:responsiblePersons,
        sharedPersonsName:sharedPersonsName,
        responsiblePersonsName:responsiblePersonsName,
        projectBuildId:this.projectBuildId
      })
      this.addNum++;
    },
    doDel(){
      if (this.selectedRowKeys == null || this.selectedRowKeys.length < 1) {
        this.$message.warning('请选择要删除的数据')
        return
      }
      var ids=[];
      for(var i=this.dataSource.length-1;i>-1;i--){
        var strId = this.dataSource[i].strId;
        if(this.selectedRowKeys.indexOf(strId)>-1){
          if(strId.indexOf('add_')==-1){
            ids.push(strId)
          }
          this.dataSource.splice(i,1)
        }
      }
      this.selectedRowKeys=[];
      if(ids.length>0){
        getAction(this.url.deleteBatch, { ids: ids.join(',') }).then((res) => {
          if (res.success) {
            this.$message.success('操作成功')
          } else {
            this.$message.warning('操作失败:', res.message)
          }
        })
      }
    },
    showLength(item,len){
      if(!item || item.length<=len){
        return item;
      }
      return item.substring(0,len)+'...';
    },
    handleOkExcel(data) {
      //debugger
      if (data == null || data.length < 1) {
        this.$message.warning('未导入有效数据')
        this.excel.visible = false
        return
      }
      if(!this.doCheck(data)){
        return;
      }

      let amountArr = []
      data.forEach((item) =>{
        if(item.sharedPersons && item.sharedPersons != ''){
          let a = item.sharedPersons.split(',')
          amountArr.push(...a)
        }
        if(item.responsiblePersons && item.responsiblePersons != ''){
          let b = item.responsiblePersons.split(',')
          amountArr.push(...b);
        }
      })
      let amountSet = new Set(amountArr)
      console.log('amountSet:',amountSet)
      //获取账号对应的名称

      let personMap = new Map()

      postAction(this.url.personListByUserNames,[...amountSet]).then((res)=>{
        let personResult;
        if(res.code == 200){
            personResult = res.result
        }
        //console.log('personResult:',JSON.stringify(personResult))
        if(personResult){
          personResult.forEach((p) => {
              personMap.set(p.username,p.realname)
          })
        }

        console.log('personMap:',personMap)
        
        data.forEach((item) => {
          //处理共享人
          if(item.sharedPersons && item.sharedPersons != ''){
            let arr01 = item.sharedPersons.split(',')
            let sharedPersonNameArr = []
            for(let account of arr01){
              if(personMap.get(account)){
                sharedPersonNameArr.push(personMap.get(account))
              }
            }
            item.sharedPersonsName = sharedPersonNameArr.toString()
          }else{
            item.sharedPersonsName = ''
          }

          //处理责任人
          if(item.responsiblePersons && item.responsiblePersons != ''){
            let arr02 = item.responsiblePersons.split(',')
            let responsiblePersonsNameArr = []
            for(let account of arr02){
              if(personMap.get(account)){
                responsiblePersonsNameArr.push(personMap.get(account))
              }
            }
            item.responsiblePersonsName = responsiblePersonsNameArr.toString()
          }else{
            item.responsiblePersonsName = ''
          }
          //加入数据到列表中
          this.doAddData(item.budgetType,item.budgetItem,item.unit,item.num,item.includeTaxPriceUnit,item.taxRate,item.noTaxPriceUnit,item.includeTaxPriceAll,item.noTaxPriceAll,item.remark,item.sharedPersons,item.responsiblePersons,item.sharedPersonsName,item.responsiblePersonsName)
        })
        console.log('处理后的数据:',JSON.stringify(data))
      })
      this.excel.visible = false
    },
    handleCancelExcel() {
      this.excel.visible = false
    },
    doImpl() {
      this.excel.visible = true
    },

    jumpHaiNa(){
      console.log('单点登录跳转到海纳')
      let resUrl = this.url.getHaiNaUrl;
      getAction(resUrl).then((res) => {
            console.log(res)
            if(res.code == 200 && res.result){
              let jumpHaiNaUrl = res.result
              console.log('success url:',jumpHaiNaUrl)
              window.open(jumpHaiNaUrl,'_blank')
            }else{
              this.$message.error('获取跳转连接失败')
            }
            
      })
    },

  },

}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';
@import '~@assets/less/hte-main.less';
@media (max-width: 1170px) {
  .page-main .container section .list-content > div.flex-num1-box {
    flex-wrap: wrap;
    > div {
      &:nth-child(1),
      &:nth-child(2) {
        width: 48%;
      }
      &:nth-child(3) {
        width: 100%;
        justify-content: flex-start;
        > span {
          margin-right: 20px;
          margin-left: 0;
        }
      }
    }
  }
  .page-main .container section .list-content > div.flex-num2-box {
    display: block;
    margin-top: 0;
  }
}
</style>